package com.clayecloud.module_login.viewModels;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.clayecloud.lib_base.action.ToastAction;
import com.clayecloud.lib_common.apis.LoginApi;
import com.clayecloud.lib_common.apis.entity.login.ClientUser;
import com.clayecloud.lib_common.room.ClientDataBase;
import com.clayecloud.lib_common.room.entity.ClientBase;
import com.clayecloud.lib_common.room.entity.ClientToken;
import com.clayecloud.lib_common.utils.GsonUtil;
import com.clayecloud.lib_common.utils.HttpUtil;
import com.clayecloud.lib_common.utils.MessageUtil;
import com.clayecloud.lib_common.utils.TempData;
import com.clayecloud.module_login.entity.LoginUser;

import io.reactivex.Observer;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginActivityViewModel extends ViewModel implements ToastAction {

    private LoginApi loginApi;

    private MutableLiveData<Integer> int_currentPager;

    private MutableLiveData<LoginUser> loginUserMutableLiveData;

    public MutableLiveData<Boolean> bool_login;

    public MutableLiveData<Boolean> getBool_login() {
        return bool_login;
    }

    public void setBool_login(MutableLiveData<Boolean> bool_login) {
        this.bool_login = bool_login;
    }

    public MutableLiveData<Integer> getCurrentPager() {
        return int_currentPager;
    }

    public void setCurrentPager(MutableLiveData<Integer> int_currentPager) {
        this.int_currentPager = int_currentPager;
    }

    public MutableLiveData<LoginUser> getLoginUserMutableLiveData() {
        return loginUserMutableLiveData;
    }

    public void setLoginUserMutableLiveData(MutableLiveData<LoginUser> loginUserMutableLiveData) {
        this.loginUserMutableLiveData = loginUserMutableLiveData;
    }

    /**
     * 初始化数据
     */
    public void loadData(){
        //初始化网络接口
        loginApi = HttpUtil.getInstance().create(LoginApi.class);
        //初始化页面ViewPager页签
        MutableLiveData<Integer> int_currentPager = new MutableLiveData<>();
        int_currentPager.setValue(0);
        setCurrentPager(int_currentPager);
        //初始化登录状态
        MutableLiveData<Boolean> bool_login = new MutableLiveData<>();
        bool_login.setValue(false);
        setBool_login(bool_login);
        //获取登录本地数据并初始化账号数据
        LoginUser loginUser = new LoginUser(false);
        MutableLiveData<LoginUser> loginUserMutableLiveData = new MutableLiveData<>();
        loginUserMutableLiveData.setValue(loginUser);
        setLoginUserMutableLiveData(loginUserMutableLiveData);
    }

    /**
     * 登录方法
     */
    public void accountLogin(){
        loginApi.login(loginUserMutableLiveData.getValue().getStr_phoneOrEmail(), loginUserMutableLiveData.getValue().getStr_password())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MessageUtil>() {
                    private Disposable disposable;
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(@NonNull MessageUtil messageUtil) {
                        if (messageUtil.getResult()){
                            if(TempData.setTempToken((String) messageUtil.getObj())){
                                getUserInfo((String) messageUtil.getObj());
                                return;
                            }
                        }
                        toast(messageUtil.getMsg());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        toast("网络请求失败，请联系管理员");
                        Log.e("accountLogin",e.getMessage());
                        disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        disposable.dispose();
                    }
                });
    }


    /**
     * 获取用户的基础信息
     */
    private void getUserInfo(String token){
        loginApi.getUserBaseInfo(token).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<MessageUtil>() {
                    private Disposable disposable;
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        disposable = d;
                    }

                    @Override
                    public void onNext(@NonNull MessageUtil messageUtil) {
                        if (messageUtil.getResult()){
                            //1.转换类型
                            ClientUser clientUser = GsonUtil.getInstance().fromJson(GsonUtil.getInstance().toJson(messageUtil.getObj()), ClientUser.class);
                            //2.存储token
                            ClientToken clientToken = new ClientToken(clientUser.getUserID(), token);
                            ClientDataBase.getClientDataBaseInstance().getClientTokenService().insertClientToken(clientToken).subscribe(new SingleObserver<Long>() {
                                private Disposable disposable;
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                    disposable = d;
                                }

                                @Override
                                public void onSuccess(@NonNull Long aLong) {
                                    if (aLong > 0) {
                                        Log.i("getUserInfo clientToken => onNext => onSuccess", "token保存成功");
                                    } else {
                                        Log.e("getUserInfo clientToken => onNext => onSuccess", "token保存失败");
                                    }
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    Log.e("getUserInfo clientToken => onNext => onError",e.getMessage());
                                }
                            });
                            //3.存储基础用户信息
                            com.clayecloud.lib_common.room.entity.ClientUser baseClientUser
                                    = new com.clayecloud.lib_common.room.entity.ClientUser(
                                            clientUser.getUserID(),
                                            clientUser.getUserName(),
                                            clientUser.getUserState(),
                                            clientUser.getUserInfoID(),
                                            1,clientUser.getUserAvatar());
                            ClientDataBase.getClientDataBaseInstance().getClientUserService().insertClientUser(baseClientUser).subscribe(new SingleObserver<Long>() {
                                private Disposable disposable;
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                    disposable = d;
                                }

                                @Override
                                public void onSuccess(@NonNull Long aLong) {
                                    if (aLong > 0) {
                                        Log.i("getUserInfo ClientUser => onNext => onSuccess", "用户基础信息保存成功");
                                    } else {
                                        Log.e("getUserInfo ClientUser => onNext => onSuccess", "用户基础信息保存失败");
                                    }
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    Log.e("getUserInfo ClientUser => onNext => onError",e.getMessage());
                                }
                            });
                            //4.存储登录用户id
                            ClientBase clientBase = new ClientBase(1,clientUser.getUserID());
                            ClientDataBase.getClientDataBaseInstance().getClientBaseService().insertClientBase(clientBase).subscribe(new SingleObserver<Long>() {
                                private Disposable disposable;
                                @Override
                                public void onSubscribe(@NonNull Disposable d) {
                                    disposable = d;
                                }

                                @Override
                                public void onSuccess(@NonNull Long aLong) {
                                    if (aLong > 0) {
                                        Log.i("getUserInfo ClientUser => onNext => onSuccess", "登录id保存成功");
                                    } else {
                                        Log.e("getUserInfo ClientUser => onNext => onSuccess", "登录id保存失败");
                                    }
                                }

                                @Override
                                public void onError(@NonNull Throwable e) {
                                    Log.e("getUserInfo clientBase => onNext => onError", e.getMessage());
                                    disposable.dispose();
                                }
                            });
                            toast("登录成功");
                            MutableLiveData<Boolean> bool_login = getBool_login();
                            bool_login.setValue(true);
                            return;
                        }
                        toast(messageUtil.getMsg());
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        toast("网络错误，请检查网络");
                        Log.e("getUserInfo",e.getMessage());
                        disposable.dispose();
                    }

                    @Override
                    public void onComplete() {
                        disposable.dispose();
                    }
                });
    }

}
